package com.workshop.interceptor;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.base.commom.ResponseUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 控制层增强器
 * @author chengluqiang
 * @since 2019-02-27 23:33
 */
@ControllerAdvice
public class ExceptionInterceper{
	
	/**
	 * 全局异常拦截器
	 * @author chenluqiang
	 * @date 2019年3月12日 上午11:37:28 
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value=Exception.class)
	public ModelAndView defaultErrorHandler(HttpServletRequest request,HttpServletResponse response, Exception e)
   {
		 e.printStackTrace();
		 ModelAndView view = new ModelAndView();
	  try {
		  if(e instanceof AuthenticationException) {
			  response.setStatus(401);
		  }else {
			  response.setStatus(400);
		  }
		  //创建json转换的类
			ObjectMapper mapper = new ObjectMapper();
			PrintWriter writer = null;
			try {
				String jsonString = mapper.writeValueAsString(ResponseUtils.error(e.getMessage(),request.getRequestURL()));
				// 避免乱码
				response.setCharacterEncoding("UTF-8");
				// 设置ContentType
				response.setContentType("application/json; charset=utf-8");
				writer = response.getWriter();
				writer.write(jsonString);
			} finally {
				writer.close();
			}
		}catch(Exception e2) {
			 e2.printStackTrace();
		}
      return view;
   }
	
}
